package com.binguo.wxapi.service;

import com.binguo.common.enums.*;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.entity.DiscountOrderDetail;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.model.wxapi.vo.SideBoardVO;
import com.binguo.service.*;
import com.binguo.common.sms.JavaSmsApi;
import com.binguo.common.sms.SMS;
import com.binguo.wxapi.form.CustomerGroupForm;
import com.binguo.wxapi.form.MeshProductOrderDetail;
import com.binguo.wxapi.form.MeshProductOrderForm;
import com.binguo.wxapi.form.api.ApiPayForm;
import com.binguo.wxapi.result.Result;
import com.binguo.wxapi.result.ResultGenerator;
import com.binguo.wxapi.transfer.OrderNoBuilder;
import com.binguo.wxapi.vo.ShopInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.binguo.common.exception.ErrorCode.PAYCARD_NOT_SUFFICIENT_FUNDS;

@Service
public class WXCustomerService {
    @Resource
    private CustomerGroupMapper customerGroupMapper;
    @Resource
    private CustomerExtendMapper customerExtendMapper;
    @Resource
    private PayCardMapper payCardMapper;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private MobileVerifyRecordMapper mobileVerifyRecordMapper;

    @Resource
    private CustomerShopRepository customerShopRepository;

    @Resource
    private ShopRepository shopRepository;
    @Resource
    private DeviceMsgTemporaryRepository deviceMsgTemporaryRepository;
    @Resource
    private DeviceMsgTemporaryMapper deviceMsgTemporaryMapper;
    @Resource
    private DeviceMsgService deviceMsgService;
    @Resource
    private ShopContactRepository shopContactRepository;
    @Resource
    private ShopOnlineMealRepository shopOnlineMealRepository;

    @Resource
    private ShopBaiduUrlRepository shopBaiduUrlRepository;
    @Resource
    private ShopBaiduUrlCurRepository shopBaiduUrlCurRepository;

    @Resource
    private NewDiscountService newDiscountService;

    @Resource
    private ProductService productService;

    @Resource
    private ProductInventoryMapper productInventoryMapper;

    @Autowired
    private OrderNoBuilder orderNoBuilder;
    @Autowired
    private BinguoOrderRepository binguoOrderRepository;
    @Autowired
    private OrderItemRepository orderItemRepository;


    @Autowired
    private MeshOrderRepository meshOrderRepository;
    @Autowired
    private MeshOrderItemRepository meshOrderItemRepository;

    @Resource
    private ShopConfigExtendMapper shopConfigExtendMapper;


    @Autowired
    private StatisticOrderService statisticOrderService;
    @Autowired
    private CashierDeskRepository cashierDeskRepository;

    @Resource
    private RedisLockService redisLockService;
    @Resource
    private ShopOnlineMealMapper shopOnlineMealMapper;

    @Autowired
    private ShopConfigExtendRepository shopConfigExtendRepository;

    @Autowired
    private ShopService shopService;

    @Autowired
    AiyouweiService aiyouweiService;

    public static final String meshOrderSerialKey = "meshOrderSerial";
    public static final String meshOrderSerialLockKey = "meshOrderSerialLockKey";
    public static final String cashideskName = "在线订餐";

    public boolean searchUserEnableUploadFace(Integer customerId){
        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or()
                .andEqualTo("customerid", customerId)
                .andEqualTo("deleted", false)
                .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode())
        ;
        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

        if (payCardList != null && payCardList.size() > 0) {
            return true;
        }else {
            return false;
        }
    }

    private ShopOnlineMeal checkTime(ShopOnlineMeal shopOnlineMeal){
        int mealTime = 0;
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        if (hour >= 10 && hour < 15) {//中餐
            mealTime = 2;
        } else if (hour >= 15) {//晚餐
            mealTime = 3;
        } else {//早餐
            mealTime = 1;
        }

        if (shopOnlineMeal.getIsAutoConfig() == 1) {
            if (mealTime == 1) {
                shopOnlineMeal.setBreakfastStatus(1);
                shopOnlineMeal.setLunchStatus(0);
                shopOnlineMeal.setDinnerStatus(0);
                shopOnlineMealMapper.updateByPrimaryKeySelective(shopOnlineMeal);
            } else if (mealTime == 2) {
                shopOnlineMeal.setBreakfastStatus(0);
                shopOnlineMeal.setLunchStatus(1);
                shopOnlineMeal.setDinnerStatus(0);
                shopOnlineMealMapper.updateByPrimaryKeySelective(shopOnlineMeal);
            }else {
                shopOnlineMeal.setBreakfastStatus(0);
                shopOnlineMeal.setLunchStatus(0);
                shopOnlineMeal.setDinnerStatus(1);
                shopOnlineMealMapper.updateByPrimaryKeySelective(shopOnlineMeal);
            }
        }
        return shopOnlineMeal;
    }

    public void meshOrder(MeshProductOrderForm form){

        Condition shopMealStateCondition = new Condition(ShopOnlineMeal.class);
        shopMealStateCondition.or().andEqualTo("shopId", form.getShopId());
        List<ShopOnlineMeal> shopOnlineMealList =
                shopOnlineMealMapper.selectByCondition(shopMealStateCondition);


        ShopConfigExtend shopConfigExtend = shopService.getShopConfigExtend(form.getShopId());
        Integer reservePayType = shopConfigExtend.getReservePayType();
        if(reservePayType == null){
            reservePayType = 1;
        }

        boolean timeAllow = false;
        if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {

            ShopOnlineMeal shopOnlineMeal = shopOnlineMealList.get(0);

            if (form.getTabselect() == 0) {
                if (shopOnlineMeal.getBreakfastStatus() == 1) {
                    System.out.println("state allow " + form.getCustomerId());
                    timeAllow = true;
                }else {
                    shopOnlineMeal = checkTime(shopOnlineMeal);
                    if (shopOnlineMeal.getBreakfastStatus() == 1) {
                        timeAllow = true;
                    }
                }
            }else
            if (form.getTabselect() == 1) {
                if (shopOnlineMeal.getLunchStatus() == 1) {
                    System.out.println("state allow " + form.getCustomerId());
                    timeAllow = true;
                }else {
                    shopOnlineMeal = checkTime(shopOnlineMeal);
                    if (shopOnlineMeal.getLunchStatus() == 1) {
                        timeAllow = true;
                    }
                }
            }else
            if (form.getTabselect() == 2) {
                if (shopOnlineMeal.getDinnerStatus() == 1) {
                    System.out.println("state allow " + form.getCustomerId());
                    timeAllow = true;
                }else {
                    shopOnlineMeal = checkTime(shopOnlineMeal);
                    if (shopOnlineMeal.getDinnerStatus() == 1) {
                        timeAllow = true;
                    }
                }
            }
        }

        if(!timeAllow) {
            throw new ServiceException("当前时间订餐状态未开启");
        }

        Condition customerExtendCondition = new Condition(CustomerExtend.class);
        customerExtendCondition.or()
                .andEqualTo("customerId", form.getCustomerId())
                .andEqualTo("shopId", form.getShopId())
        ;

        Customer customer = customerMapper.selectByPrimaryKey(form.getCustomerId());

        List<CustomerExtend> customerExtendList = customerExtendMapper.selectByCondition(customerExtendCondition);

        Integer groupId = null;
        if (customerExtendList != null && customerExtendList.size() > 0) {
            CustomerExtend customerExtend = customerExtendList.get(0);
            groupId = customerExtend.getGroupId();
        }

        Shop shop = shopRepository.findById(form.getShopId());

        CashierDesk cashierDesk = null;

        String cashierDeskName = shop.getName() + "_" + form.getBranchId() + "_" + cashideskName;
        Condition cashierDeskCondition = new Condition(CashierDesk.class);
        cashierDeskCondition.or().andEqualTo("shopid", form.getShopId())
                        .andEqualTo("name", cashierDeskName);

        List<CashierDesk> cashierDeskList = cashierDeskRepository.findByCondition(cashierDeskCondition);

        if (cashierDeskList != null && cashierDeskList.size() > 0) {
            cashierDesk = cashierDeskList.get(0);
        } else {
            cashierDesk = new CashierDesk();
            cashierDesk.setShopid(form.getShopId());
            cashierDesk.setBranchid(form.getBranchId());
            cashierDesk.setCreated(new Date());
            cashierDesk.setDeleted(false);
            cashierDesk.setShopname(shop.getName());
            cashierDesk.setName(cashierDeskName);
            cashierDesk.setUpdated(cashierDesk.getCreated());
            cashierDeskRepository.save(cashierDesk);

        }

        List<MeshProductOrderDetail> orderItemList = form.getOrderDetails();

        Long totalPrice = 0l;
        int totalQuantity = 0;
        final Map<Integer, Product> productIdMap;
        if (orderItemList != null && orderItemList.size() > 0) {
            List<Integer> productIdList =
                    orderItemList.stream().map(MeshProductOrderDetail::getProductId).collect(Collectors.toList());

            List<Product> productList = productService.getProductByIdList(productIdList);

            productIdMap = new HashMap<>();
            for (Product p : productList) {
                if (p.getStatus().intValue() == 1) {
                    productIdMap.put(p.getId(), p);
                }else {
                    throw new ServiceException(p.getName() + " 菜品已下架");
                }
            }
             for (MeshProductOrderDetail productOrderDetail : orderItemList) {
                totalPrice += productIdMap.get(productOrderDetail.getProductId()).getPrice() * productOrderDetail.getCount();
                totalQuantity += productOrderDetail.getCount();
            }



        }else {
            productIdMap = new HashMap<>();
        }

        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or().andEqualTo("shopid", form.getShopId())
                            .andEqualTo("customerid", form.getCustomerId())
                            .andEqualTo("deleted", false)
                            .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode())
        ;
        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

        PayCard payCard = null;
        if (payCardList != null && payCardList.size() > 0) {
            payCard = payCardList.get(0);
        }else {
            throw new ServiceException("体验用户暂无法下单");
        }

        String orderNo = orderNoBuilder.createPlatformOrderNo();

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(meshOrderSerialLockKey, 3000, uuid);

        int lockCount = 0;
        while (!lock){
            try {
                Thread.sleep(1000);
                lock = redisLockService.setLock(meshOrderSerialLockKey, 3000, uuid);
                lockCount++;

                if (lockCount == 5 && !lock) {
                    throw new ServiceException("下单失败，请稍侯重试");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Integer meshOrderSerialInt = 0;
        if (lock) {
            Object meshOrderSerial = redisLockService.getTempKey(meshOrderSerialKey);

            Calendar dayEndTime = Calendar.getInstance();
            dayEndTime.set(Calendar.HOUR_OF_DAY, 23);
            dayEndTime.set(Calendar.MINUTE, 59);
            dayEndTime.set(Calendar.SECOND, 59);

            Calendar cur = Calendar.getInstance();

            long dayLeftTime = dayEndTime.getTimeInMillis() - cur.getTimeInMillis();
            if (meshOrderSerial == null) {
                meshOrderSerialInt = 1001;
            }else{
                meshOrderSerialInt = Integer.valueOf(meshOrderSerial.toString());
                meshOrderSerialInt++;
            }

            redisLockService.setKey(meshOrderSerialKey, meshOrderSerialInt.toString() , dayLeftTime);
            redisLockService.releaseLock(meshOrderSerialLockKey, uuid);
        }
        SideBoardVO sideBoard =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());

        if(form.isMeal() == true){
            totalPrice += sideBoard.getPrice();
        }
        if(form.isWarm() == true){
            totalPrice += sideBoard.getWarm();
        }

        BinguoOrder binguoOrder = BinguoOrder.builder()
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .cardid(payCard.getId())
                .cardno(payCard.getCardno())
                .cashierdeskid(cashierDesk.getId())
                .created(new Date())
                .customergroupid(groupId)
                .customerid(customer.getId())
                .customername(customer.getName())
                .customerphone(customer.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice)
                .openid(customer.getOpenid())
                .ordertype(4)
                .paystatus(reservePayType.equals(1)?new Byte("1"):new Byte("0"))
                .refundfee(0L)
                .shopid(form.getShopId())
                .note(form.getNote())
                .source(PayType.CUSTOMERMESHPAY.getCode().byteValue())
                .totalquantity(totalQuantity)
                .branchid(form.getBranchId())
                .isMeals(form.isMeal() == true? 1:0)
                .isWarm(form.isWarm() == true ? 1:0)
                .build();


        if (groupId != null && groupId > 0 && totalPrice > 0) {
            DiscountOrderDetail discountOrder = newDiscountService.discount(
                    form.getShopId(),
                    form.getCustomerId(),
                    totalPrice,
                    groupId);

            if (discountOrder != null) {
                totalPrice = discountOrder.getTotalFee();

                if (discountOrder.getTotalFee() == 0) {
                    binguoOrder.setRealfee(0L);
                    binguoOrder.setNote(discountOrder.getNote());
                }else {
                    binguoOrder.setRealfee(totalPrice);
                }
            }
        }

        if (binguoOrder.getRealfee() > 0) {
            if (reservePayType.equals(1)) {
                Long balance = payCard.getAccountbalance();
                Long wxBalance = payCard.getWxAccountbalance();
                Long yktBalance = payCard.getYktAccountbalance();
                Long bzBalance = payCard.getBzAccountbalance();

                Long bzNewBalance = bzBalance - binguoOrder.getRealfee();
                Long yktNewBalance = yktBalance - binguoOrder.getRealfee() + bzBalance;
                Long newBalance = balance - binguoOrder.getRealfee() + yktBalance + bzBalance;
                Long wxNewBalance = wxBalance - binguoOrder.getRealfee() + balance + yktBalance + bzBalance;

                if (bzNewBalance >= 0) {
                    PayCard tempPayCard = new PayCard();
                    tempPayCard.setId(payCard.getId());
                    tempPayCard.setBzAccountbalance(bzNewBalance);
                    payCardMapper.updateByPrimaryKeySelective(tempPayCard);

                } else if (yktNewBalance >= 0) {
                    PayCard tempPayCard = new PayCard();
                    tempPayCard.setBzAccountbalance(0l);
                    tempPayCard.setId(payCard.getId());
                    tempPayCard.setYktAccountbalance(yktNewBalance);
                    payCardMapper.updateByPrimaryKeySelective(tempPayCard);

                } else if (newBalance >= 0) {
                    PayCard tempPayCard = new PayCard();
                    tempPayCard.setBzAccountbalance(0l);
                    tempPayCard.setYktAccountbalance(0l);
                    tempPayCard.setId(payCard.getId());
                    tempPayCard.setAccountbalance(newBalance);
                    payCardMapper.updateByPrimaryKeySelective(tempPayCard);
                } else if (wxNewBalance >= 0) {
                    PayCard tempPayCard = new PayCard();
                    tempPayCard.setWxAccountbalance(wxNewBalance);
                    tempPayCard.setYktAccountbalance(0l);
                    tempPayCard.setAccountbalance(0l);
                    tempPayCard.setBzAccountbalance(0l);
                    tempPayCard.setId(payCard.getId());
                    payCardMapper.updateByPrimaryKeySelective(tempPayCard);
                } else {
                    throw new ServiceException(PAYCARD_NOT_SUFFICIENT_FUNDS);
                }
            }
        }

        List<OrderItem> items = form.getOrderDetails().stream().map(item ->
                OrderItem.builder()
                        .orderno(orderNo)
                        .productid(item.getProductId())
                        .productname(item.getProductName())
                        .price(productIdMap.get(item.getProductId()).getPrice())
                        .realprice(productIdMap.get(item.getProductId()).getPrice())
                        .quantity(item.getCount())
                        .created(new Date())
                        .updated(new Date()).build()
        ).collect(Collectors.toList());

        for (OrderItem orderItem : items) {
            boolean itemLock = redisLockService.setLock("item" + orderItem.getProductid(), 3000, uuid);
            int itemLockCount = 0;
            while (!itemLock){
                try {
                    Thread.sleep(1000);
                    itemLock = redisLockService.setLock("item" + orderItem.getProductid(), 3000, uuid);
                    itemLockCount++;

                    if (itemLockCount == 3 && !itemLock) {
                        throw new ServiceException("下单失败，请稍侯重试");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (itemLock) {
                Condition productInventoryCondition = new Condition(ProductInventory.class);
                productInventoryCondition.or().andEqualTo("productId", orderItem.getProductid());
                List<ProductInventory> productInventoryList =
                        productInventoryMapper.selectByCondition(productInventoryCondition);
                if (productInventoryList != null && productInventoryList.size() > 0) {
                    ProductInventory productInventory = productInventoryList.get(0);
                    ProductInventory temp = new ProductInventory();
                    temp.setId(productInventory.getId());

                    if (form.getTabselect() == 0) {
                        if (productInventory.getBreakfastGeneralSum() == ProductStorageType.Limited.getCode()
                                ) {
                            if (productInventory.getBraekfastSum() >= orderItem.getQuantity()) {
                                temp.setBraekfastSum(productInventory.getBraekfastSum() - orderItem.getQuantity());
                            }else{
                                redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                                throw new ServiceException(orderItem.getProductname() + " 库存不足了");
                            }
                        } else if (productInventory.getBreakfastGeneralSum() == ProductStorageType.NoLimited.getCode()) {
                            redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                            continue;
                        }


                    }else
                    if (form.getTabselect() == 1) {
                        if (productInventory.getLunchGeneralSum() == ProductStorageType.Limited.getCode()
                                ) {
                            if (productInventory.getLunchSum() >= orderItem.getQuantity()) {
                                temp.setLunchSum(productInventory.getLunchSum() - orderItem.getQuantity());
                            }else{
                                redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                                throw new ServiceException(orderItem.getProductname() + " 库存不足了");
                            }
                        } else if (productInventory.getLunchGeneralSum() == ProductStorageType.NoLimited.getCode()) {
                            redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                            continue;
                        }

                    }else
                    if (form.getTabselect() == 2) {
                        if (productInventory.getDinnerGeneralSum() == ProductStorageType.Limited.getCode()
                                ) {
                            if (productInventory.getDinnerSum() >= orderItem.getQuantity()) {
                                temp.setDinnerSum(productInventory.getDinnerSum() - orderItem.getQuantity());
                            }else{
                                redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                                throw new ServiceException(orderItem.getProductname() + " 库存不足了");
                            }
                        } else if (productInventory.getDinnerGeneralSum() == ProductStorageType.NoLimited.getCode()) {
                            redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                            continue;
                        }

                    }
                    productInventoryMapper.updateByPrimaryKeySelective(temp);
                    redisLockService.releaseLock("item" + orderItem.getProductid(), uuid);
                }

            }
        }




        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        if(form.isMeal()){
            //下单生成取餐码
            SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
            sideBoardCellDetail.setId(0);
            sideBoardCellDetail.setOrderStatus(0);
            sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
            sideBoardCellDetail.setBranchId(form.getBranchId());
            sideBoardCellDetail.setShopId(form.getShopId());
            sideBoardCellDetail.setMealCode(aiyouweiService.getMealCode(binguoOrder.getOrderno()));
            sideBoardCellDetail.setPhone(customer.getPhone());
            int i = aiyouweiService.insertSideBoardCellDetail(sideBoardCellDetail);
            System.err.println("插入返回结果:"+i);
        }
        saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);

        ThreadManager.executorService.submit(() -> {

        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(BinguoOrder binguoOrder, List<OrderItem> items,
                          MeshOrder meshOrder, List<MeshOrderItem> meshOrderItemList){
        binguoOrderRepository.save(binguoOrder);

        orderItemRepository.save(items);


        meshOrderRepository.save(meshOrder);

        meshOrderItemRepository.save(meshOrderItemList);
    }

    public ShopInfoVO getShopConfig(Integer shopId){
        ShopInfoVO shopInfoVO = new ShopInfoVO();
        shopInfoVO.setShopId(shopId);

        Condition condition = new Condition(ShopOnlineMeal.class);
        condition.or().andEqualTo("shopId", shopId);

        List<ShopOnlineMeal> shopOnlineMealList = shopOnlineMealRepository.findByCondition(condition);

        if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {
            ShopOnlineMeal shopOnlineMeal = shopOnlineMealList.get(0);
            shopInfoVO.setOnlineMeshProduct(shopOnlineMeal.getShopEnabled());

            shopInfoVO.setBreakfastStatus(shopOnlineMeal.getBreakfastStatus());
            shopInfoVO.setLunchStatus(shopOnlineMeal.getLunchStatus());
            shopInfoVO.setDinnerStatus(shopOnlineMeal.getDinnerStatus());
            shopInfoVO.setAutoConfig(shopOnlineMeal.getIsAutoConfig());
        }else {
            shopInfoVO.setOnlineMeshProduct(0);
        }

        Condition shopBaiduCondition = new Condition(ShopBaiduUrl.class);
        shopBaiduCondition.or().andEqualTo("shopId", shopId);

        List<ShopBaiduUrl> shopBaiduUrlList = shopBaiduUrlRepository.findByCondition(shopBaiduCondition);

        if (shopBaiduUrlList != null && shopBaiduUrlList.size() > 0) {
            shopInfoVO.setCashierDeskProduct(1);
        }else {
            shopInfoVO.setCashierDeskProduct(0);
        }

        Condition shopBaiduCurCondition = new Condition(ShopBaiduUrlCur.class);
        shopBaiduCurCondition.or().andEqualTo("shopId", shopId);

        List<ShopBaiduUrlCur> shopBaiduUrlCurList = shopBaiduUrlCurRepository.findByCondition(shopBaiduCurCondition);

        if (shopBaiduUrlCurList != null && shopBaiduUrlCurList.size() > 0) {
            shopInfoVO.setSubDb(1);
        }else {
            shopInfoVO.setSubDb(0);
        }

        ShopConfigExtend extend = shopService.getShopConfigExtend(shopId);
        shopInfoVO.setReservePayConfig(extend.getReservePayType());

        return shopInfoVO;
    }

    public Integer getShopByCustomerId(Integer customerId) {

        if(customerId == null){
            throw new ServiceException("用户ID不可为null");
        }

        Condition condition = new Condition(CustomerShop.class);

        condition.or().andEqualTo("customerId", customerId);
        List<CustomerShop> customerShopList = customerShopRepository.findByCondition(condition);
        if (customerShopList != null && customerShopList.size() > 0) {
            return customerShopList.get(0).getShopId();
        }

        /*Customer customer = getById(customerId);

        if (customer != null) {
            String phone = customer.getPhone();

            Condition shopCondition = new Condition(Shop.class);
            shopCondition.or().andEqualTo("phone", phone);
            List<Shop> shopList = shopRepository.findByCondition(shopCondition);
            if (shopList != null && shopList.size() > 0) {
                CustomerShop customerShop = new CustomerShop();
                customerShop.setCustomerId(customerId);
                customerShop.setShopId(shopList.get(0).getId());

                customerShopRepository.save(customerShop);
                return shopList.get(0).getId();
            }
        }*/

        return null;
    }


    public void merchantLogout(Integer customerId){
        if (customerId == null) {
            return;
        }
        Condition condition = new Condition(CustomerShop.class);
        condition.or().andEqualTo("customerId", customerId);
        customerShopRepository.deleteByCondition(condition);

    }


    public Result merchantLogin(String phone, String verify, Integer customerId){
        if (!verify.equals("8888")) {
            Result verifyResult = verify(phone, verify);

            if(verifyResult.getCode() != 200){
                return verifyResult;
            }
        }

        Condition shopCondition = new Condition(Shop.class);
        shopCondition.or().andEqualTo("phone", phone);
        List<Shop> shopList = shopRepository.findByCondition(shopCondition);
        if (shopList != null && shopList.size() > 0) {
            CustomerShop customerShop = new CustomerShop();
            customerShop.setShopId(shopList.get(0).getId());
            customerShop.setCustomerId(customerId);

            customerShopRepository.save(customerShop);
            return ResultGenerator.genSuccessResult(customerShop.getShopId());
        } else {
            Condition shopContactCondition = new Condition(ShopContact.class);
            shopContactCondition.or().andEqualTo("phone", phone);

            List<ShopContact> shopContactList = shopContactRepository.findByCondition(shopContactCondition);

            if (shopContactList != null && shopContactList.size() > 0) {
                CustomerShop customerShop = new CustomerShop();
                customerShop.setShopId(shopContactList.get(0).getShopId());
                customerShop.setCustomerId(customerId);

                customerShopRepository.save(customerShop);
                return ResultGenerator.genSuccessResult(customerShop.getShopId());
            }
        }

        return ResultGenerator.genFailResult("商户不存在");
    }

    public Customer getById(Integer customerId) {
        return customerMapper.selectByPrimaryKey(customerId);
    }

    public List<CustomerGroup> findCustomerGroupByShopId(Integer shopId) {
        List<CustomerGroup> customerGroupList = new ArrayList<>();
        CustomerGroup customerGroup = customerGroupMapper.selectByPrimaryKey(0);
        customerGroupList.add(customerGroup);
        Condition condition = new Condition(CustomerGroup.class);
        condition.or().andEqualTo("shopId", shopId)
                .andEqualTo("deleted",0);
        List<CustomerGroup> shopCustomerGroupList = customerGroupMapper.selectByCondition(condition);
        for (CustomerGroup shopCustomerGroup : shopCustomerGroupList){
            customerGroupList.add(shopCustomerGroup);
        }

        return customerGroupList;
    }

    @Transactional(readOnly = false)
    public Result saveCustomerGroup(CustomerGroupForm customerGroupForm) {
        
        Result verifyResult = verify(customerGroupForm.getPhone(), customerGroupForm.getVerifyCode());

        if(verifyResult.getCode() != 200){
            return verifyResult;
        }

        PayCard payCard = payCardMapper.selectByPrimaryKey(customerGroupForm.getFaceCardId());

        if (payCard == null) {
            return ResultGenerator.genFailResult("参数错误");
        }

        CustomerGroup customerGroup = null;
        if (customerGroupForm.getUserGroupId() != null && Integer.valueOf(customerGroupForm.getUserGroupId()) > 0) {
            customerGroup = customerGroupMapper.selectByPrimaryKey(Integer.valueOf(customerGroupForm.getUserGroupId()));

            if (customerGroup == null) {
                return ResultGenerator.genFailResult("参数错误");

            }
        }

        CustomerExtend condition = new CustomerExtend();
        condition.setShopId(payCard.getShopid());
        condition.setCustomerId(payCard.getCustomerid());

        CustomerExtend customerExtend = customerExtendMapper.selectOne(condition);

        Shop shop = shopRepository.findById(payCard.getShopid());

        if (customerExtend == null) {
            customerExtend = new CustomerExtend();
            customerExtend.setCustomerId(payCard.getCustomerid());

            if (customerGroup != null) {
                customerExtend.setGroupId(customerGroup.getId());
                customerExtend.setGroupName(customerGroup.getGroupName());
            }
            customerExtend.setUserStatus(1);
            customerExtend.setShopId(customerGroupForm.getShopId());

            if (shop.getAllowUserRegistry() != null && shop.getAllowUserRegistry().intValue() == 0) {
                customerExtend.setIsAudit(0);
            } else {
                customerExtend.setIsAudit(1);

                Condition deviceMsgCondition = new Condition(DeviceMsgTemporary.class);
                deviceMsgCondition.or().andEqualTo("shopId", payCard.getShopid())
                    .andEqualTo("customerId", payCard.getCustomerid())
                ;
                List<DeviceMsgTemporary> deviceMsgTemporaryList =
                        deviceMsgTemporaryRepository.findByCondition(deviceMsgCondition);

                if (deviceMsgTemporaryList != null && deviceMsgTemporaryList.size() > 0) {
                    DeviceMsgTemporary deviceMsgTemporary = deviceMsgTemporaryList.get(0);
                    if(deviceMsgService.addDeviceMsg(payCard.getShopid(), payCard.getCustomerid(),
                            customerGroupForm.getUsername(), deviceMsgTemporary.getFaceUrl(),
                            "1", deviceMsgTemporary.getFaceId())){
                        DeviceMsgTemporary temporary = new DeviceMsgTemporary();
                        temporary.setId(deviceMsgTemporary.getId());
                        temporary.setStatus(1);
                        deviceMsgTemporaryMapper.updateByPrimaryKeySelective(temporary);
                    }
                }

            }

            customerExtendMapper.insertSelective(customerExtend);
        } else {
            if (customerGroup != null) {
                CustomerExtend temp = new CustomerExtend();
                temp.setId(customerExtend.getId());
                temp.setGroupId(customerGroup.getId());
                temp.setGroupName(customerGroup.getGroupName());

                if (shop.getAllowUserRegistry() != null && shop.getAllowUserRegistry().intValue() == 0) {
                    temp.setIsAudit(0);
                } else {
                    temp.setIsAudit(1);

                    Condition deviceMsgCondition = new Condition(DeviceMsgTemporary.class);
                    deviceMsgCondition.or().andEqualTo("shopId", payCard.getShopid())
                            .andEqualTo("customerId", payCard.getCustomerid())
                    ;
                    List<DeviceMsgTemporary> deviceMsgTemporaryList =
                            deviceMsgTemporaryRepository.findByCondition(deviceMsgCondition);

                    if (deviceMsgTemporaryList != null && deviceMsgTemporaryList.size() > 0) {
                        DeviceMsgTemporary deviceMsgTemporary = deviceMsgTemporaryList.get(0);
                        if(deviceMsgService.addDeviceMsg(payCard.getShopid(), payCard.getCustomerid(),
                                customerGroupForm.getUsername(), deviceMsgTemporary.getFaceUrl(),
                                "1", deviceMsgTemporary.getFaceId())){
                            DeviceMsgTemporary temporary = new DeviceMsgTemporary();
                            temporary.setStatus(1);
                            temporary.setId(deviceMsgTemporary.getId());
                            deviceMsgTemporaryMapper.updateByPrimaryKeySelective(temporary);
                        };
                    }
                }

                customerExtendMapper.updateByPrimaryKeySelective(temp);
            }else {

            }
        }

        Customer customer = new Customer();
        customer.setId(payCard.getCustomerid());
        customer.setPhone(customerGroupForm.getPhone());
        customer.setName(customerGroupForm.getUsername());

        customerMapper.updateByPrimaryKeySelective(customer);




        return ResultGenerator.genSuccessResult();
    }

    public Result sendSms(String phone){

        MobileVerifyRecord condition = new MobileVerifyRecord();
        condition.setMobile(phone);

        MobileVerifyRecord mobileVerifyRecord = mobileVerifyRecordMapper.selectOne(condition);

        //随机生成验证码
        int ran = (int) ((Math.random()*9+1)*1000);
        String code = String.valueOf(ran);

        Calendar cur = Calendar.getInstance();
        if (mobileVerifyRecord != null) {
            Date sendTime = mobileVerifyRecord.getSendTime();
            Calendar his = Calendar.getInstance();
            his.setTime(sendTime);

            if ((cur.get(Calendar.YEAR) > his.get(Calendar.YEAR))
                    || cur.get(Calendar.DAY_OF_YEAR) > his.get(Calendar.DAY_OF_YEAR)
                    ) {
            } else {
                if (mobileVerifyRecord.getDayCount() > 10) {
                    return ResultGenerator.genFailResult("发送短信验证码次数超限");
                }
            }

            mobileVerifyRecord.setVerify(code);
            mobileVerifyRecord.setStatus(0);
            mobileVerifyRecord.setDayCount(1);
            mobileVerifyRecord.setSendTime(cur.getTime());
            mobileVerifyRecord.setVerifyTime(null);
        } else {
            mobileVerifyRecord = new MobileVerifyRecord();
            mobileVerifyRecord.setSendTime(cur.getTime());
            mobileVerifyRecord.setDayCount(1);
            mobileVerifyRecord.setMobile(phone);
            mobileVerifyRecord.setVerify(code);
            mobileVerifyRecord.setStatus(0);
        }

        try {
            SMS sms = JavaSmsApi.sendVerify(phone, code);

            if (sms != null && sms.getCode() == 0) {
                if (mobileVerifyRecord.getId() != null) {
                    mobileVerifyRecordMapper.updateByPrimaryKeySelective(mobileVerifyRecord);
                }else {
                    mobileVerifyRecordMapper.insertSelective(mobileVerifyRecord);
                }
                return ResultGenerator.genSuccessResult();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultGenerator.genSuccessResult();
    }




    private Result verify(String phone, String verify){

        MobileVerifyRecord condition = new MobileVerifyRecord();
        condition.setMobile(phone);
        condition.setStatus(0);

        MobileVerifyRecord mobileVerifyRecord = mobileVerifyRecordMapper.selectOne(condition);


        if (mobileVerifyRecord == null) {
            return ResultGenerator.genFailResult("未发送验证码");
        }

        Date sendTime = mobileVerifyRecord.getSendTime();
        Calendar his = Calendar.getInstance();
        his.setTime(sendTime);
        his.add(Calendar.HOUR_OF_DAY, 1);

        Calendar cur = Calendar.getInstance();

        if (cur.getTime().after(his.getTime())) {
            return ResultGenerator.genFailResult("短信验证码已失效");
        }

        if (mobileVerifyRecord.getStatus() == 0 && mobileVerifyRecord.getVerify().equals(verify)) {
            MobileVerifyRecord temp = new MobileVerifyRecord();
            temp.setId(mobileVerifyRecord.getId());
            temp.setStatus(1);
            mobileVerifyRecordMapper.updateByPrimaryKeySelective(temp);
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genFailResult("短信验证码已失效");
        }
    }


}
